package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.dto.product.CategoryExcelDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.spzx.model.pojo.product.Category;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author admin
 * @description 针对表【category(商品分类)】的数据库操作Service实现
 * @createDate 2025-01-05 20:21:05
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findByParentId(Long parentId) {
        List<Category> categorys = categoryMapper.selectList(new QueryWrapper<Category>().eq("parent_id", parentId));
        for (Category category : categorys) {
            Long id = categoryMapper.selectCount(new QueryWrapper<Category>().eq("parent_id", category.getId()));
            if (id <= 0) {
                category.setHasChildren(false);
            }
        }
        return categorys;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        // 查询所有数据并放回为categoryDto
        List<Category> list = categoryMapper.selectList(null);
        List<CategoryExcelDto> dtoList = new ArrayList<>();
        for (Category category : list) {
            CategoryExcelDto categoryExcelDto = new CategoryExcelDto();
            categoryExcelDto.setId(category.getId());
            categoryExcelDto.setName(category.getName());
            categoryExcelDto.setStatus(category.getStatus());
            categoryExcelDto.setImageUrl(category.getImageUrl());
            categoryExcelDto.setOrderNum(category.getOrderNum());
            dtoList.add(categoryExcelDto);
        }
        try {
            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            EasyExcel.write(response.getOutputStream(), CategoryExcelDto.class).sheet("分类数据").doWrite(dtoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}




